package main

import (
	"fmt"
	"net"
	"sync"
)

type Server struct {
	IP        string
	Port      int
	OnlineMap map[string]*User //用来存储上线的用户
	Messag    chan string      //用来广播需要发送给用户的消息
	Lock      sync.RWMutex
}

//创建服务
func NewServer(ip string, port int) *Server {
	return &Server{
		IP:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Messag:    make(chan string),
	}
}

//服务启动
func (s *Server) Start() {
	//设置监听
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.IP, s.Port))
	if err != nil {
		fmt.Println("net.Listen err:", err)
		return
	}
	defer listen.Close()

	//开启go程开启消息监听
	go s.ListenMsg()

	for {
		//建立链接
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("listen.Accept err", err)
			return
		}
		defer conn.Close()
		go s.HandlerServer(conn)

	}

}

//处理主要业务
func (s *Server) HandlerServer(conn net.Conn) {

	//根据链接创建用户
	user := NewUser(conn, s)
	user.Online()

	//读取用户客户端发来的数据
	go user.HandlerServer()

}

//将用户发送的消息发送到server的chann中
func (s *Server) BroadCast(u *User, msg string) {

	BroadCastMsg := fmt.Sprintf("「%s」:%s", u.Name, msg)

	s.Messag <- BroadCastMsg

}

//监听server中 channel 中的消息，将里面的消息发送给每个用户的channel
func (s *Server) ListenMsg() {
	for {
		msg := <-s.Messag
		s.Lock.Lock()
		for _, user := range s.OnlineMap {
			user.C <- msg
		}
		s.Lock.Unlock()
	}
}
